<template>
  <div class="audio">
    <audio id="audio" :src="audioSrc.absolute_url"></audio>
    <div class="box">
      <div :class="play ? 'pause' : 'play'" @click="playAudio"></div>
      <el-progress :percentage="progress" type="line" :show-text="false" />
      <div class="time"> {{ startTime }}/{{ endTime }} </div>
      <el-icon @click="closeFun"><close-bold /></el-icon>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import bus from '@/utils/bus'
  import { Zero } from '@/utils/cycletime'

  const audioSrc = ref({})
  const startTime = ref('00:00')
  const endTime = ref('00:00')
  const progress = ref(0)
  const play = ref(false)

  const preview = (item: any) => {
    audioSrc.value = item.media_file
    setTimeout(() => {
      audioTime()
    }, 200)
  }

  const closeFun = () => {
    bus.emit('audio')
  }

  const playAudio = () => {
    let audio = document.querySelector('#audio')

    let startime = setInterval(() => {
      if (startTime.value === endTime.value) {
        play.value = !play.value
        clearInterval(startime)
      }
      playTime()
    }, 1000)

    if (!play.value) {
      audio.play()
      startime
      play.value = !play.value
    } else {
      audio.pause()
      clearInterval(startime)
      play.value = !play.value
    }
  }

  const audioTime = () => {
    let audio = document.querySelector('#audio')
    let end = `${Zero(Math.floor(audio.duration / 60))}:${Zero(Math.floor(audio.duration % 60))}`
    endTime.value = end
  }

  const playTime = () => {
    let audio = document.querySelector('#audio')
    let start = `${Zero(Math.floor(audio.currentTime / 60))}:${Zero(Math.floor(audio.currentTime % 60))}`

    let percent = (audio.currentTime / audio.duration) * 100
    progress.value = percent

    startTime.value = start
  }

  bus.on('preview', preview)
</script>

<style scoped lang="scss">
  .audio {
    width: 300px;
    height: 50px;
    position: absolute;
    top: 20px;
    right: 50px;
    border-radius: 25px;
    display: flex;
    background: white;
    .box {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-evenly;
      .play {
        width: 30px;
        height: 30px;
        z-index: 2;
        background: url('@/assets/image/material/play.png') no-repeat;
        background-size: cover;
        cursor: pointer;
      }
      .pause {
        width: 15px;
        height: 15px;
        z-index: 2;
        background: url('@/assets/image/material/suspend_icon.png') no-repeat;
        background-size: cover;
        cursor: pointer;
      }
      .el-progress {
        width: 150px;
        height: 20px;
      }
      .time {
        font-size: 10px;
      }
      .el-icon {
        z-index: 20;
      }
    }
  }
</style>
